﻿using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using StackExchange.Profiling;
using System.Data;
namespace FI.Dapper.Transaction
{
    public class DapperContext : IDapperContext
    {

        private readonly string _connectionString;
        private bool _useMiniProfiler;
        private IDbConnection _connection;

        public DapperContext(string connectionString = "DefaultConnection")
        {
            var temp = ConfigManager.Get("UseProfiler");
            if (!bool.TryParse(temp, out _useMiniProfiler))
            {
                _useMiniProfiler = false;
            }

            _connectionString = ConfigManager.Configuration.GetConnectionString(connectionString); ;
        }

        public IDbConnection Connection
        {
            get
            {
                if (_connection == null)
                {
                    if (_useMiniProfiler)
                    {
                     
                        _connection = new StackExchange.Profiling.Data.ProfiledDbConnection(new MySqlConnection(_connectionString), MiniProfiler.Current);
                         
                    }
                    else
                    {
                        _connection = new MySqlConnection(_connectionString);
                    }
                }
                if (_connection.State != ConnectionState.Open)
                {
                    _connection.Open();
                }
                return _connection;
            }
        }

        public IDbTransaction Transaction { get; set; }


        public void Dispose()
        {
            if (_connection != null && _connection.State == ConnectionState.Open)
                _connection.Close();
        }
    }
}